package com.mmall.controller.protal;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;

/**
 * 支付模块
 * Created by qujian on 2017/7/14.
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController {

    @Autowired
    private IOrderService iOrderService;

    private final Logger  logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 创建订单
     * @param session
     * @param shippingId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create.do")
    public ServerResponse create(HttpSession session,Integer shippingId){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.createOrder(user.getId(),shippingId);
    }

    /**
     * 取消订单(暂时未对接支付宝 进行退款)
     * @param session
     * @param orderNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancel.do")
    public ServerResponse cancel(HttpSession session,Long orderNo){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.cancelOrder(user.getId(),orderNo);
    }


    /**
     * 获取购物车中选中的物品详细
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_order_cart_product.do")
    public ServerResponse getOrderCartProduct(HttpSession session){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderCartProduct(user.getId());
    }


    /**
     * 获取订单详情
     * @param session
     * @param orderNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detail.do")
    public ServerResponse detail(HttpSession session,Long orderNo){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderdetail(user.getId(),orderNo);
    }


    /**
     * 获取用户的订单列表
     * @param session
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.do")
    public ServerResponse<PageInfo> list(HttpSession session,
                                         @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderList(user.getId(),pageNum,pageSize);
    }
































    /**
     * 对接支付宝支付
     * @param session
     * @param orderNo
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pay.do")
    public ServerResponse pay(HttpSession session, Long orderNo, HttpServletRequest request) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                ResponseCode.NEED_LOGIN.getDesc());
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return iOrderService.pay(user.getId(), orderNo, path);
    }

    /**
     * 支付宝回调处理接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/alipay_callback.do")
    public Object alipayCallback(HttpServletRequest request) {
        Map maps = Maps.newHashMap();
        Map requestParameterMap = request.getParameterMap();
        for (Iterator iterator = requestParameterMap.keySet().iterator(); iterator.hasNext();) {
            String name = (String) iterator.next();
            String[] values = (String[]) requestParameterMap.get(name);
            String valuesStr = "";
            for (int i = 0; i < values.length; i++) {
                valuesStr = (i == values.length - 1) ? valuesStr + values[i]
                    : valuesStr + values[i] + ",";
            }
            maps.put(name, valuesStr);
        }
        logger.info("支付宝回调，sign:{},trade_status:{},参数{}", maps.get("sign"),
                maps.get("trade_status"), maps.toString());
        maps.remove("sign_type");
        try {
            boolean alipaySignature = AlipaySignature.rsaCheckV2(maps, Configs.getAlipayPublicKey(),
                "utf-8", Configs.getSignType());
            if (!alipaySignature) {
                return ServerResponse.createByErrorMessage("非法请求，验证不通过,再恶意请求我就报警啦");
            }
        } catch (AlipayApiException e) {
            logger.error("支付宝回调验证异常");
            e.printStackTrace();
        }
        //todo 验证数据

        ServerResponse serverResponse = iOrderService.aliCallback(maps);
        if (serverResponse.isSuccess()) {
            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;
    }

    /**
     * 查询订单支付状态
     * @param session
     * @param orderNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query_order_pay_status.do")
    public ServerResponse<Boolean> queryOrderPayStatus(HttpSession session,Long orderNo){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        ServerResponse serverResponse = iOrderService.queryOrderPayStatus(user.getId(),orderNo);
        if(serverResponse.isSuccess()){
            return ServerResponse.createBySuccess(true);
        }
        return ServerResponse.createBySuccess(false);
    }
}
